import 'dart:io';
import 'dart:math';
import 'dart:ui';

import 'package:cave_flutter/common/common_widget.dart';
import 'package:cave_flutter/common/sliver_header_delegate.dart';
import 'package:cave_flutter/config/whl_global_config.dart';
import 'package:cave_flutter/db_manager/bean/whl_product_bean.dart';
import 'package:cave_flutter/model/user_model.dart';
import 'package:cave_flutter/pages/whl_home/rank_list_widget.dart';
import 'package:cave_flutter/routes/whl_app_pages.dart';
import 'package:cave_flutter/utils/extension/string_extension.dart';
import 'package:cave_flutter/widgets/brick/brick.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../common/common_action.dart';
import '../../style/whl_style.dart';
import '../../widgets/refresh_widget.dart';
import 'whl_home_logic.dart';

class WhlHomePage extends StatelessWidget {
  WhlHomePage({Key? key}) : super(key: key);

  final logic = Get.put(WhlHomeLogic());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: kAppColor('#F8F8F8'),
        appBar: AppBar(
          elevation: 0,
          backgroundColor: kAppColor('#F8F8F8'),
          title: UIText(
            text: 'Cave',
            alignment: Alignment.center,
            textColor: kAppTextColor,
            fontSize: 16.sp,
            fontWeight: FontWeight.bold,
          ),
        ),
        body: MyRefresh(
          controller: logic.refreshController,
          onRefresh: () {
            logic.onRefresh();
          },
          childBuilder: (context, physics) {
            return ExtendedNestedScrollView(
              physics: physics,
              headerSliverBuilder:
                  (BuildContext context, bool innerBoxIsScrolled) {
                return [
                  SliverPersistentHeader(
                    delegate: MySliverHeaderDelegate(
                      maxHeight: 130.w,
                      child: Swiper(
                        itemBuilder: (BuildContext context, int index) {
                          return UIImage(
                            // margin: EdgeInsets.only(right: 10.w),
                            assetImage: 'icon_home_top_$index.png',
                            fit: BoxFit.fill,
                            // width: 130.w,
                            // height: 130.w,
                            onTap: () {
                              logic.doClickTopBanner(index);
                            },
                          );
                        },
                        itemCount: 3,
                        viewportFraction: 130.w / ScreenUtil().screenWidth,
                        scale: 0.7,
                      ),
                    ),
                  ),
                  SliverPersistentHeader(
                    pinned: true,
                    delegate: MySliverHeaderDelegate(
                      maxHeight: 55.h,
                      minHeight: 55.h,
                      child: UIRow(
                        padding: EdgeInsets.only(left: 18.w),
                        color: kAppColor('#F8F8F8'),
                        children: [
                          UIRow(
                            children: logic.tabList.map((e) {
                              int index = logic.tabList.indexOf(e);
                              return GetBuilder<WhlHomeLogic>(builder: (logic) {
                                return UIText(
                                  margin: EdgeInsets.only(right: 21.w),
                                  text: e.title,
                                  textColor: logic.selectedTabIndex == index
                                      ? kAppTextColor
                                      : kAppColor('#9C9C9C'),
                                  fontSize: logic.selectedTabIndex == index
                                      ? 22.sp
                                      : 16.sp,
                                  fontWeight: logic.selectedTabIndex == index
                                      ? FontWeight.bold
                                      : FontWeight.normal,
                                  onTap: () {
                                    logic.selectedTabIndex = index;
                                    logic.update();
                                  },
                                );
                              });
                            }).toList(),
                          ),
                          Expanded(child: Container()),
                          UIImage(
                            assetImage: 'icon_home_search.png',
                            width: 38.w,
                            decoration: BoxDecoration(boxShadow: [
                              BoxShadow(
                                color: Colors.black.withOpacity(0.07),
                                offset: const Offset(0, 8),
                                blurRadius: 30,
                              )
                            ]),
                            onTap: () {
                              Get.toNamed(Routes.search)?.then((value) {
                                if (value != null) {
                                  logic.setNearbyQueryParams(
                                    {'nickName': value},
                                  );
                                }
                              });
                            },
                          ),
                          UIImage(
                            margin: EdgeInsets.only(left: 8.w, right: 13.w),
                            assetImage: 'icon_home_screen.png',
                            width: 38.w,
                            decoration: BoxDecoration(boxShadow: [
                              BoxShadow(
                                color: Colors.black.withOpacity(0.07),
                                offset: const Offset(0, 8),
                                blurRadius: 30,
                              )
                            ]),
                            onTap: () {
                              Get.toNamed(
                                Routes.screen,
                                // arguments: logic.nearbyQueryParams,
                              )?.then((value) {
                                if (value != null) {
                                  logic.setNearbyQueryParams(value);
                                }
                              });
                            },
                          ),
                        ],
                      ),
                    ),
                  ),
                ];
              },
              body: GetBuilder<WhlHomeLogic>(builder: (logic) {
                if (logic.selectedTabIndex == 0) {
                  return buildCardSwiperView();
                } else if (logic.selectedTabIndex == 1) {
                  return buildNearbyView(physics);
                } else {
                  return const RankListWidget();
                }
              }),
            );
          },
        ));
  }

  Widget buildCardSwiperView() {
    return Stack(
      clipBehavior: Clip.none,
      children: [
        Positioned(
          bottom: -24.w,
          left: 70.w,
          right: 70.w,
          child: UIImage(
            assetImage: 'img_home_card_boxshadow.png',
            width: 235.w,
            height: 27.w,
            fit: BoxFit.fill,
          ),
        ),
        SizedBox(
          height: 388.w,
          child: Swiper(
            itemBuilder: (BuildContext context, int index) {
              return UIColumn(
                margin: EdgeInsets.symmetric(horizontal: 7.5.w),
                color: Colors.white,
                radius: 22.w,
                children: [
                  Stack(
                    children: [
                      UIImage(
                        assetImage: 'img_art_detail_0.jpg',
                        width: 265.w,
                        height: 214.w,
                        fit: BoxFit.cover,
                        radius: 22.w,
                      ),
                      Align(
                        alignment: Alignment.topRight,
                        child: UIImage(
                          margin: EdgeInsets.only(top: 13.w, right: 11.w),
                          assetImage: 'img_home_card_online.png',
                          width: 64.w,
                        ),
                      ),
                      UIRow(
                        margin: EdgeInsets.only(top: 283.w, left: 18.w),
                        children: [
                          UIText(
                            margin: EdgeInsets.only(right: 6.w),
                            padding: EdgeInsets.symmetric(
                                horizontal: 8.w, vertical: 2.h),
                            color: kAppColor('#FFEEC4').withOpacity(0.9),
                            radius: 6.w,
                            text: '羽毛球',
                            textColor: kAppColor('#FFD600'),
                            fontSize: 11.sp,
                            fontWeight: FontWeight.bold,
                          ),
                          UIText(
                            margin: EdgeInsets.only(right: 6.w),
                            padding: EdgeInsets.symmetric(
                                horizontal: 8.w, vertical: 2.h),
                            color: kAppColor('#FEF6FB').withOpacity(0.9),
                            radius: 6.w,
                            text: '羽毛球',
                            textColor: kAppColor('#FF73A0'),
                            fontSize: 11.sp,
                            fontWeight: FontWeight.bold,
                          ),
                          UIText(
                            margin: EdgeInsets.only(right: 6.w),
                            padding: EdgeInsets.symmetric(
                                horizontal: 8.w, vertical: 2.h),
                            color: kAppColor('#F2FEFE').withOpacity(0.6),
                            radius: 6.w,
                            text: '小网红',
                            textColor: kAppColor('#33A9FF'),
                            fontSize: 11.sp,
                            fontWeight: FontWeight.bold,
                          ),
                        ],
                      )
                    ],
                  ),
                  Row(
                    children: [
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                UIText(
                                  margin: EdgeInsets.only(top: 6.w, left: 17.w),
                                  text: '祖儿',
                                  textColor: kAppTextColor,
                                  alignment: Alignment.centerLeft,
                                  fontSize: 18.sp,
                                  fontWeight: FontWeight.bold,
                                ),
                                UIText(
                                  margin: EdgeInsets.only(left: 2.w),
                                  padding: EdgeInsets.symmetric(
                                      horizontal: 6.w, vertical: 3.w),
                                  color: kAppColor('#F4EEFF'),
                                  text: 'LV.11',
                                  textColor: kAppTextColor,
                                  fontSize: 11.sp,
                                  radius: 100,
                                )
                              ],
                            ),
                            UIText(
                              margin: EdgeInsets.only(top: 2.w, left: 17.w),
                              text: '168玫瑰蛇，打视频响铃久一 点,温柔有趣',
                              textColor: kAppColor('#9C9C9C'),
                              fontSize: 11.sp,
                              alignment: Alignment.centerLeft,
                              shrinkWrap: false,
                            )
                          ],
                        ),
                      ),
                      UIText(
                        margin: EdgeInsets.only(right: 10.w),
                        text: '80币/min',
                        height: 38.w,
                        padding: EdgeInsets.symmetric(horizontal: 10.w),
                        textColor: kAppTextColor,
                        alignment: Alignment.center,
                        radius: 24.w,
                        fontSize: 12.sp,
                        fontWeight: FontWeight.bold,
                        startDrawable: UIImage(
                          assetImage: 'icon_home_card_call.png',
                          width: 15.w,
                        ),
                        color: kAppColor('#FFE800'),
                      )
                    ],
                  )
                ],
              );
            },
            itemCount: 10,
            viewportFraction: 0.75,
            // scale: 0.9,
          ),
        ),
      ],
    );
  }

  buildNearbyView(
    ScrollPhysics physics,
  ) {
    return Column(
      children: [
        UIRow(
          margin: EdgeInsets.only(left: 17.w, right: 9.w),
          padding:
              EdgeInsets.only(left: 18.w, right: 10.w, top: 10.w, bottom: 10.w),
          radius: 12.w,
          color: Colors.white,
          children: [
            UIImage(
              assetImage: 'icon_location.png',
              width: 14.w,
            ),
            UIText(
              margin: EdgeInsets.only(left: 7.w, right: 9.w),
              text: '漫游到其他城市',
              textColor: kAppTextColor,
              fontSize: 12.sp,
              fontWeight: FontWeight.w500,
            ),
            Flexible(
                child: UIText(
              margin: EdgeInsets.only(right: 25.w),
              text: logic.locationDescription,
              textColor: kAppTextColor,
              fontSize: 12.sp,
              fontWeight: FontWeight.bold,
              overflow: TextOverflow.ellipsis,
              endDrawable: Icon(
                Icons.keyboard_arrow_right,
                color: kAppColor('#CCCCCC'),
              ),
              onTap: () {
                logic.goMapSearchPage();
                // Get.toNamed(Routes.userInfo,arguments: "112317");
              },
            ))
          ],
        ),
        Expanded(
          child: CustomScrollView(
            physics: physics,
            slivers: [
              SliverList(
                  delegate: SliverChildBuilderDelegate((context, index) {
                UserModel model = logic.nearbyList[index];
                return UIRow(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  margin: EdgeInsets.only(top: 13.w, left: 13.w, right: 13.w),
                  padding: EdgeInsets.only(bottom: 15.w),
                  radius: 16.w,
                  color: Colors.white,
                  boxShadow: [
                    BoxShadow(
                        offset: const Offset(0, 0),
                        color: kAppColor('#221A38').withOpacity(0.02),
                        blurRadius: 30)
                  ],
                  children: [
                    UIImage(
                      margin:
                          EdgeInsets.only(left: 16.w, top: 14.w, right: 7.w),
                      httpImage: model.avatar?.toImageUrl(),
                      assetPlaceHolder: WHLGlobalConfig.userPlaceholderAvatar,
                      width: 45.w,
                      height: 45.w,
                      radius: 45.w,
                    ),
                    Expanded(
                        child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            UIText(
                              margin: EdgeInsets.only(top: 10.w, bottom: 8.w),
                              text: model.nickName,
                              textColor: kAppTextColor,
                              fontSize: 16.sp,
                              fontWeight: FontWeight.bold,
                            ),
                            model?.levelImage != null
                                ? UIImage(
                                    margin: EdgeInsets.only(left: 4.w),
                                    // assetImage: 'icon_svip.png',
                                    httpImage: model?.levelImage?.toImageUrl(),
                                    disabledHttpBigImage: true,

                                    width: 18.w,
                                    height: 18.w,
                                  )
                                : Container(),
                            // UIText(
                            //   padding: EdgeInsets.symmetric(
                            //       horizontal: 4.w, vertical: 3.w),
                            //   margin: EdgeInsets.only(left: 4.w),
                            //   text: 'Lv${model.level}',
                            //   alignment: Alignment.center,
                            //   textColor: kAppTextColor,
                            //   fontSize: 8.sp,
                            //   radius: 7.w,
                            //   color: kAppColor("#FFE9B6"),
                            // ),
                            // UIImage(
                            //   margin: EdgeInsets.only(left: 4.w),
                            //   assetImage: 'icon_svip.png',
                            //   width: 51.w,
                            // )
                          ],
                        ),
                        Row(
                          children: [
                            UIText(
                              padding: EdgeInsets.only(left: 8.w, right: 7.w),
                              height: 18.w,
                              alignment: Alignment.center,
                              text: '${model.age.toString()}岁',
                              textColor: getGenderColor(model.gender),
                              fontSize: 11.sp,
                              color: kAppColor('#F6F6F6'),
                              radius: 6.w,
                              marginDrawable: 3.w,
                              startDrawable: UIImage(
                                assetImage: getGenderIcon(model.gender),
                                height: 10.w,
                              ),
                            ),
                            UIText(
                              margin: EdgeInsets.only(left: 4.w),
                              padding: EdgeInsets.only(left: 8.w, right: 7.w),
                              height: 18.w,
                              alignment: Alignment.center,
                              text: model.sexualOrientation ?? '未知',
                              textColor: kAppColor('#444444'),
                              fontSize: 11.sp,
                              color: kAppColor('#F6F6F6'),
                              radius: 6.w,
                            ),
                            UIText(
                              margin: EdgeInsets.only(left: 4.w),
                              padding: EdgeInsets.only(left: 8.w, right: 7.w),
                              height: 18.w,
                              alignment: Alignment.center,
                              text: model.funRole ?? "未知",
                              textColor: kAppColor('#444444'),
                              fontSize: 11.sp,
                              color: kAppColor('#F6F6F6'),
                              radius: 6.w,
                            ),
                            Expanded(child: Container()),
                            UIText(
                              margin: EdgeInsets.only(right: 17.w),
                              text:
                                  '${model.distance?.toDouble()}km · 当前${model.onlineStatus == true ? "在线" : "不在线"}',
                              textColor: kAppColor('#9C9C9C'),
                              fontSize: 10.sp,
                            )
                          ],
                        ),
                        if ((model.album ?? []).isNotEmpty)
                          UIRow(
                            margin: EdgeInsets.only(top: 14.w, bottom: 19.w),
                            children: [
                              for (int i = 0;
                                  i <
                                      (model.album!.length > 3
                                          ? 3
                                          : model.album!.length);
                                  i++)
                                UIImage(
                                  margin: EdgeInsets.only(right: 4.w),
                                  httpImage:
                                      model.album![i]!.toString().toImageUrl(),
                                  assetPlaceHolder: 'icon_app_logo.png',
                                  fit: BoxFit.fill,
                                  width: 83.w,
                                  height: 83.w,
                                  radius: 12.w,
                                ),
                            ],
                          )
                      ],
                    ))
                  ],
                  onTap: () {
                    Get.toNamed(Routes.userInfo, arguments: {
                      "accountId": model.accountId,
                      "userId": model.userId
                    });
                  },
                );
              }, childCount: logic.nearbyList.length)),
              SliverToBoxAdapter(
                child: SizedBox(
                  height: 50,
                ),
              )
            ],
          ),
        )
      ],
    );
  }
}
